package cn.samler.shopapi.Interceptor;

import cn.samler.shopapi.Annotation.IgnoreTokenCheck;
import cn.samler.shopapi.Entity.User;
import cn.samler.shopapi.Model.Sys.Response;
import cn.samler.shopapi.Service.UserService;
import cn.samler.shopapi.Utils.JWTUtil;
import cn.samler.shopapi.Utils.PasswordUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.regex.Pattern;

@Component
@Slf4j
public class JWTInterceptor implements HandlerInterceptor {
    private final UserService userService;
    private final JWTUtil jwtUtil;

    JWTInterceptor(UserService userService, JWTUtil jwtUtil) {
        this.userService = userService;
        this.jwtUtil = jwtUtil;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("access_token");
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod))
            return true;

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        // 检查是否需要进行jwt拦截检测
        if (!method.isAnnotationPresent(IgnoreTokenCheck.class)) {
            DecodedJWT jwtObj = (token != null && Pattern.matches("[\\w-]+\\.[\\w-]+\\.[\\w-]+", token)) ? jwtUtil.verify(token) : null;
            if (jwtObj != null) {
                JSONObject json = jwtUtil.getPayload(jwtObj);
                Integer uid = (Integer) (json.getOrDefault("uid", null));
                if (uid != null) {
                    User user = userService.findById(uid);

                    //验证是否修改过密码
                    if (user == null || jwtUtil.isAvailable(jwtObj, "token", user.getToken())) {
                        //如果需要重新创建一个token 则通知客户端保存新的toekn 并且将新的token返回
                        if (jwtUtil.isNeedRefresh(jwtObj)) {
                            JSONObject resp = new JSONObject();
                            resp.put("access_token", jwtUtil.sign(user.getPayload()));
                            result(response, Response.getInstance(1000, "access token refreshed", resp));
                            return false;
                        }

                        request.setAttribute("current_user", user);
                        return true;
                    } else log.debug("password changed");
                } else log.debug("uid is null");
            } else log.debug("jwtObj is null");

            //验证未通过
            result(response, Response.getInstance(1001, "access token invalid", null));
            return false;
        }

        return true;
    }

    private void result(HttpServletResponse response, Response result) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.setStatus(200);
        PrintWriter out;
        try {
            out = response.getWriter();
            out.append(JSON.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
